package main

import (
	"context"
	"fmt"
	"net"
	"strconv"

	"gitee.com/go-micro-services/consul-grpc/protos/users"
	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
)

// 定义通用度变量, 这里以后可以做成配置，仅做简单举例
var (
	host    string = "127.0.0.1"
	port    int    = 9000
	portStr string = strconv.Itoa(port)
	address        = host + ":" + portStr
)

type Users struct {
	users.UnimplementedUsersServer
}

func (g Users) AddUser(c context.Context, req *users.AddUserReq) (*users.AddUserRes, error) {
	fmt.Println(req)
	return &users.AddUserRes{
		Success: true,
		Message: "增加用户成功",
	}, nil
}

func (g Users) GetUser(c context.Context, req *users.GetUserReq) (*users.GetUserRes, error) {
	var tempList []*users.UsersModel
	for i := 0; i < 10; i++ {
		tempList = append(tempList, &users.UsersModel{
			Name: "商品" + strconv.Itoa(i),
			Age:  int32(i),
		})
	}
	return &users.GetUserRes{
		UserList: tempList,
	}, nil
}

func main() {
	// ----------------------- 1. 注册consul服务 -----------------------
	// 1、初始化consul配置
	consulConfig := api.DefaultConfig()
	consulConfig.Address = "127.0.0.1:8500" // consul服务的默认地址可省略，如果不是本机，需要补充

	// 2、获取consul操作对象
	consulClient, _ := api.NewClient(consulConfig)

	// 3、配置注册服务的参数
	agentService := api.AgentServiceRegistration{
		ID:      "uuu-1", // 不要重复
		Tags:    []string{"test"},
		Name:    "Users-Service",
		Port:    port, // 和下面 grpc server 的配置相同, 否则就连接不上微服务
		Address: host, // 同上
		Check: &api.AgentServiceCheck{
			GRPC:                           address,
			Timeout:                        "3s",
			Interval:                       "1s",
			DeregisterCriticalServiceAfter: "5s",
		},
	}
	//  4、注册服务到consul上
	consulClient.Agent().ServiceRegister(&agentService)
	// ----------------------- 2. 注册GRPC -----------------------
	// 1、获取Grpc示例
	grpcServer := grpc.NewServer()
	// 2、注册服务
	users.RegisterUsersServer(grpcServer, &Users{})
	// 3. 健康检查
	grpc_health_v1.RegisterHealthServer(grpcServer, health.NewServer())
	// 4、监听端口
	listener, err := net.Listen("tcp", address)
	if err != nil {
		fmt.Println(err)
	}
	// 5、退出服务的时候关闭监听
	defer listener.Close()
	// 6、启动服务
	grpcServer.Serve(listener)
}
